package com.k2data.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by ChenJingShuai on 2017/11/17.
 */
public class FileUtils {
    public static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);

    // 路径分隔符.
    public static final String PATH_SEPARATOR = "/";

    /**
     * 递归获取指定目录下的所有文件名.
     *
     * @param dirPath 目录的路径.
     * @param isWithPath 返回的文件名是不是包含输入的目录路径.
     *
     * @return null代表目录不存在; empty代表目录下没文件.
     *
     * @see File#listFiles()
     */
    public static List<String> getFileNameList(String dirPath, boolean isWithPath) {
        List<String> fileNameList;

        File directory = new File(dirPath);
        if (directory.isDirectory()) {
            fileNameList = new LinkedList<>();
            File[] files = directory.listFiles();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("The file names in directory named {}:{}.", dirPath, files);
            }

            for (File file : files) {
                if (file.isFile()) {
                    String fileName = file.getName();
                    if (isWithPath) {
                        fileNameList.add(file.getAbsolutePath());
                    } else {
                        fileNameList.add(fileName);
                    }
                } else {
                    fileNameList.addAll(getFileNameList(file.getPath(), isWithPath));
                }
            }
        } else {
            LOGGER.warn("{} is not a directory.", dirPath);
            fileNameList = null;
        }

        return fileNameList;
    }
}
